<!-- 奖品管理-->
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="static/js/jquery-3.4.1.min.js"></script>
    <script src="static/layui/layui.js"></script>
    <script src="static/js/util.js"></script>
    <link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<body>
<!-- 卡片搜索面板-->
<div style="padding: 20px; background-color: #F2F2F2;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header"><span style="margin-right: 10px; margin-bottom: 2px" class="layui-badge-dot"></span>快速搜索</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px">
                        <label class="layui-form-label">卡券名称</label>
                        <div class="layui-input-block" style="width: 200px">
                            <input id="search-input-name" type="text" name="title" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="dept-insert">
    <form class="layui-form" method="post">
        <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">卡券名称</label>
            <div class="layui-input-block">
                <input id="dept-name" name="name" required  lay-verify="required" placeholder="请输入卡券名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="padding-right: 50px">
            <label class="layui-form-label">卡券库存</label>
            <div class="layui-input-block">
                <#--  <textarea id="dept-awardCount" name="awardCount" placeholder="请输入卡券库存" class="layui-input"></textarea>  -->
                <input id="dept-awardCount" type="tel" name="awardCount" required  lay-verify="required" placeholder="请输入卡券库存" autocomplete="off" class="layui-input" oninput = "value=value.replace(/[^\d]/g,'')" maxlength="10">
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="padding-right: 50px">
            <label class="layui-form-label">卡券ID</label>
            <div class="layui-input-block">
                <#--  <textarea id="dept-ticketId" name="ticketId" placeholder="请输入卡券ID" class="layui-input"></textarea>  -->
                <input id="dept-ticketId" type="tel" name="ticketId" required  lay-verify="required" placeholder="请输入卡券ID" autocomplete="off" class="layui-input" oninput = "value=value.replace(/[^\d]/g,'')" maxlength="10">
            </div>
        </div>
    </form>

</script>

<table class="layui-hide" id="dept-table" lay-filter="dept-table"></table>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addDept">添加卡券</button>
    </div>
</script>

<script type="text/html" id="barTpl">
    <a class="layui-btn layui-btn-xs" lay-event="edit">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
    layui.use('table', function(){
        let table = layui.table;
        table.render({
            elem: '#dept-table',
            url:'${request.contextPath}/award',
            toolbar: '#toolbar',
            parseData: function (res) {
                console.log("parseData==========");
                console.log(res);
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.size,
                    data: res.data
                }
            }
            ,cols: [[
                {field:'id', width:80, title: 'ID'},
                {field:'name', width:150, title: '卡券名称', edit: true},
                {field:'awardCount', width:120, title:'剩余库存', edit: true},
                {field:'ticketId', width:120, title:'卡券ID', edit: true},
                {field:'createdTime', width:180, title: '创建时间', sort: true},
                {field:'updatedTime', width:180, title: '修改时间', sort: true},
                {field:'changeUser', width:180, title: '修改人', sort: true},
                {fixed: 'right', width:150, align:'center', toolbar: '#barTpl'}
            ]]
            ,page: true
        });

        table.on('toolbar(dept-table)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            switch(obj.event){
                case 'addDept':
                    layer.open({
                        btn: '新建',
                        title: '添加卡券',
                        content: $("#dept-insert").text(),
                        offset: 'c',
                        area: ["500px", "300px"],
                        yes: function () {
                            var name = $("#dept-name").val();
                            var awardCount = $("#dept-awardCount").val();
                            var ticketId = $("#dept-ticketId").val();

                            name = stringFilter(name)
                            name = name.replace(/ /g,'')

                            if (name.length <= 0  || awardCount.length <= 0 || ticketId.length <= 0) {
                                if (!name) {
                                    layer.tips('卡券名称不能为空', '#dept-name',  {
                                        tipsMore: true
                                    });
                                }
                                if (awardCount.length <= 0) {
                                    layer.tips('卡券库存不能为空', '#dept-awardCount', {
                                        tipsMore: true
                                    });
                                }
                                if (ticketId.length <= 0) {
                                    layer.tips('卡券ID不能为空', '#dept-ticketId', {
                                        tipsMore: true
                                    });
                                }
                            } else {
                                if(!check_nonnegative(awardCount)){
                                    layer.tips('卡券库存格式错误', '#dept-awardCount', {
                                        tipsMore: true
                                    });
                                    return;
                                }
                                
                                // 调用新建API
                                let nowDate = new Date();
                                $.ajax({
                                    url: '${request.contextPath}/award',
                                    method: 'post',
                                    data: {
                                        name: name,
                                        awardCount: awardCount,
                                        ticketId: ticketId,
                                        createdTime: nowDate
                                    },
                                    success: function (res) {
                                        console.log(res);
                                        if (res.code == 200) {
                                            // 执行局部刷新, 获取之前的TABLE内容, 再进行填充
                                            var dataBak = [];
                                            var tableBak = table.cache.dept-table;
                                            for (var i = 0; i < tableBak.length; i++) {
                                                dataBak.push(tableBak[i]);      //将之前的数组备份
                                            }
                                            dataBak.push({
                                                name: $("#dept-name"),
                                                awardCount: $("#dept-awardCount"),
                                                ticketId: $("#dept-ticketId"),
                                                createdTime: nowDate
                                            });
                                            //console.log(dataBak);
                                            table.reload("dept-table",{
                                                data:dataBak   // 将新数据重新载入表格
                                            });
                                            layer.msg('新建卡券成功', {icon: 1});
                                        } else {
                                            layer.msg('新建卡券失败: '+res.msg, {icon: 2});
                                        }
                                    }
                                });
                            }
                        }
                    });
            }
        });

        //监听工具条(右侧)
        table.on('tool(dept-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'edit'){ //编辑
                data.name = stringFilter(data.name)
                // 发送更新请求
                $.ajax({
                    url: '${request.contextPath}/award',
                    method: 'put',
                    data: JSON.stringify({
                        id: data.id,
                        name: data.name,
                        ticketId:data.ticketId,
                        awardCount: data.awardCount
                    }),
                    contentType: "application/json",

                    success: function (res) {
                        console.log(res);
                        if (res.code == 200) {
                            layer.msg('更改卡券信息成功', {icon: 1});
                            table.reload("dept-table");
                            // obj.update({
                            //     name: data.name,
                            //     awardCount: data.awardCount
                            // });
                        } else {
                            layer.msg('更改卡券信息失败: '+res.msg, {icon: 2});
                            table.reload("dept-table");
                        }
                    }
                });
            } else if (layEvent == 'del') {
                layer.confirm('删除卡券' + data.name + '?', {skin: 'layui-layer-molv',offset:'c', icon:'0'},function(index){
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: '${request.contextPath}/award/' + data.id,
                        type: 'delete',
                        success: function (res) {
                            console.log(res);
                            if (res.code == 200) {
                                layer.msg('删除卡券成功', {icon: 1, skin: 'layui-layer-molv', offset:'c'});
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            } else {
                                layer.msg(res.msg, {icon: 2, skin: 'layui-layer-molv', offset:'c'});
                            }
                        }
                    })
                });
            }
        });

        /* 搜索实现, 使用reload, 进行重新请求 */
        $("#search-input-name").on('input',function () {
            search(table);
        });

        function search(table) {
            // 用来传递到后台的查询参数MAP
            let whereData = {};
            let qname = $("#search-input-name").val();

            if (qname.length > 0) whereData["qname"] = qname;
            table.reload("dept-table",{
                where: {
                    query: JSON.stringify(whereData)
                }
                ,page: {
                    curr: 1
                }
            });
        }

    });




</script>
</body>
</html>